/*
 * Copyright (C) 2012 Artem Bakulin
 *
 * This file is part of Speech Fluency for Android
 * (http://code.google.com/p/speech-fluency-droid/)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.google.code.speechfluency;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;

/**
 * Background service that manages delayed audio feedback threads
 * 
 * @author Artem Bakulin
 */
public class DelayedAudioFeedbackService extends Service {
    
    private DelayedAudioWorker worker;
    private Settings settings;
    private boolean onCall;
    private boolean headsetConnected;
    
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    
    @Override
    public void onCreate() {
        getTelephonyManager().listen(
                phoneStateListener,
                PhoneStateListener.LISTEN_CALL_STATE);
        
        registerReceiver(
                headsetStateReceiver,
                new IntentFilter(Intent.ACTION_HEADSET_PLUG));
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent == null) {
            return START_STICKY;
        }
        
        Settings newSettings = Settings.extractFromIntent(intent);
        if (newSettings == null || !newSettings.equals(this.settings)) {
            this.settings = newSettings;
            stopRecordingIfRunning();
            startRecordingIfNecessary();
        }
        
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        stopRecordingIfRunning();
        getTelephonyManager().listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);
        unregisterReceiver(headsetStateReceiver);
    }
    
    private void phoneStateChanged(boolean onCall) {
        this.onCall = onCall;
        stopRecordingIfRunning();
        startRecordingIfNecessary();
    }
    
    private void headsetStateChanged(boolean connected) {
        this.headsetConnected = connected;
        if (settings != null && settings.isMuteWithoutHeadset()) {
            stopRecordingIfRunning();
            startRecordingIfNecessary();
        }
    }
    
    private void startRecordingIfNecessary() {
        if (settings == null) {
            return;
        }
        
        if (!settings.isActive()) {
            return;
        }
        
        if (settings.isMuteWithoutHeadset() && !headsetConnected) {
            return;
        }
        
        worker = new DelayedAudioWorker(settings, onCall);
        worker.start();
    }
    
    private void stopRecordingIfRunning() {
        if (worker != null) {
            worker.stopRecording();
            worker = null;
        }
    }
    
    private TelephonyManager getTelephonyManager() {
        return (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
    }
    
    private final PhoneStateListener phoneStateListener = new PhoneStateListener() {

        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            Log.i(Logging.TAG, "Telephony state was changed: state=" + state);
            phoneStateChanged(state == TelephonyManager.CALL_STATE_OFFHOOK);
        }
    };
    
    private final BroadcastReceiver headsetStateReceiver = new BroadcastReceiver() {
        
        @Override
        public void onReceive(Context context, Intent intent) {
            int state = intent.getIntExtra("state", -1);
            int micro = intent.getIntExtra("microphone", -1);
            String name = intent.getStringExtra("name");
            Log.i(Logging.TAG, "Headset state was changed: " +
                               "state=" + state + ", " +
                               "microphone=" + micro + ", " +
                               "name=" + name);
            
            boolean connected = state != 0;
            boolean hasMicrophone = micro != 0 ;
            headsetStateChanged(connected && hasMicrophone);
        }
    };
}
